package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@EnableWebSecurity //拦截所有请求
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启细粒度控制
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    MyAuthenctiationSuccessHandler myAuthenctiationSuccessHandler;

    //配置拦截资源 首页所有人可以访问 功能页只有对应有权限的人才能访问
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //请求的规则
        http.authorizeRequests()
                .antMatchers("/static/upload/**","/static/**","/toLogin").permitAll()//所有人都能访问
                .anyRequest().authenticated();
//                .antMatchers("/level1/**").hasRole("vip1")
//                .antMatchers("/level2/**").hasRole("vip2")
//                .antMatchers("/level3/**").hasRole("vip3");
        //开启登录页面
        http.formLogin().loginPage("/toLogin") //登录页
                .usernameParameter("username").passwordParameter("password")//设置表单用户名和密码
                .loginProcessingUrl("/login")//登录表单请求
                .successHandler(myAuthenctiationSuccessHandler);//登录成功

        http.csrf().disable();//关闭csrf
        http.logout().logoutSuccessUrl("/toLogin")
                .invalidateHttpSession(true);//注销成功去首页
        //权限不够返回处理
        http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest req, HttpServletResponse resp,
                               AccessDeniedException e) throws IOException, ServletException {
                String type = req.getHeader("X-Requested-With");
                if("XMLHttpRequest".equals(type)){
                    resp.getWriter().print("403");
                }else{
                    req.getRequestDispatcher("/error403").forward(req,resp);
                }
            }
        });

        //开启记住我 cookie的实现
        http.rememberMe().rememberMeParameter("remember");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //(1)基于内存认证方式
//        auth.inMemoryAuthentication()
//                .withUser("ks").password("123456").roles("vip2","vip3")
//                .and()
//                .withUser("root").password("123456").roles("vip1","vip2","vip3");
        //(2)基于数据库认证方式
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }



    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode("123");
        System.out.println(encode);
    }

}

